package com.example.administrator.szb.activity.webviews;

import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.RequiresApi;
import android.text.TextUtils;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.administrator.szb.R;
import com.example.administrator.szb.activity.base.BasePresenter;
import com.example.administrator.szb.activity.base.MVPBaseActivity;
import com.example.administrator.szb.common.CommonPost;
import com.example.administrator.szb.common.ReslutBean;
import com.example.administrator.szb.http.OnResultListener;
import com.example.administrator.szb.http.URLAddress;
import com.example.administrator.szb.util.CallOtherOpeanFile;
import com.example.administrator.szb.util.CheckInfoUtils;
import com.example.administrator.szb.util.Contants;
import com.example.administrator.szb.util.Permission;
import com.example.administrator.szb.util.QTLog;
import com.example.administrator.szb.util.ShareUtils;
import com.example.administrator.szb.util.Toasts;
import com.example.administrator.szb.view.FuJianPop;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

public class WebViewsActivity extends MVPBaseActivity {
    private TextView bar_title;
    private ImageView right_img,right_sc,fujian;
    private WebView webview_webview;
    private String url;
    private int type;
    private int id=0;
    private boolean showShoucang = false;
    private List<String> list;
    private List<String> nameList;
    private List<String> urlList;
    private String titles="";
    private String contents="";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web_views);

    }

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected void setScreen() {

    }

    @Override
    protected void initView() {
        titles = getIntent().getStringExtra("titles");
        contents = getIntent().getStringExtra("contents");
        showShoucang = getIntent().getBooleanExtra("show",false);
        type = getIntent().getIntExtra("type",0);
        id = getIntent().getIntExtra("id",0);
        fujian = findViewById(R.id.fujian);
        right_sc = findViewById(R.id.right_sc);
        if (showShoucang){
            right_sc.setVisibility(View.VISIBLE);
        }
        bar_title = findViewById(R.id.bar_title);
        right_img = findViewById(R.id.right_img);
        webview_webview = findViewById(R.id.webview_webview);
    }
    private boolean isShowFujian = false;
    private void init(){

        if (list!=null){
            nameList = new ArrayList<>();
            urlList = new ArrayList<>();
            for (int i=0;i<list.size();i++){
                String str = list.get(i);

                str = str.replace("{","");
                str = str.replace("}","");
                str = str.replace("\"","");
                QTLog.e(str);
                String[] tmpList = str.split(":");
                nameList.add(Contants.getFileName("/"+tmpList[0]));
                urlList.add(tmpList[1]);
            }
        }
    }


private int select = -1;
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void initEvent() {
        initShucang();
        isShowFujian = getIntent().getBooleanExtra("showFuJian",false);
        list = getIntent().getStringArrayListExtra("list");
        init();
        if (isShowFujian&&list!=null&&list.size()>0){
            fujian.setVisibility(View.VISIBLE);
        }
        url = getIntent().getStringExtra("url");
        if (TextUtils.isEmpty(url)){
            url = "http://www.baidu.com";
        }

        WebSettings webSettings = webview_webview.getSettings();
//支持缩放，默认为true。
        webSettings .setSupportZoom(true);
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
//让缩放显示的最小值为起始
        webview_webview.setInitialScale(5);
//调整图片至适合webview的大小
        webSettings .setUseWideViewPort(true);
// 缩放至屏幕的大小
        webSettings .setLoadWithOverviewMode(true);
//设置默认编码
        webSettings .setDefaultTextEncodingName("utf-8");
////设置自动加载图片
        webSettings .setLoadsImagesAutomatically(true);


        webview_webview.loadUrl(url);
        webview_webview.setWebChromeClient(new WebChromeClient());

//如果访问的页面中要与Javascript交互，则webview必须设置支持Javascript
        webview_webview.getSettings().setJavaScriptEnabled(true);
//设置自适应屏幕，两者合用
        webSettings.setUseWideViewPort(true); //将图片调整到适合webview的大小
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT){
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        webSettings.setBlockNetworkImage(false);
        right_img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ShareUtils.share(WebViewsActivity.this,null,url+"&app=1",titles,contents);
            }
        });
        fujian.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FuJianPop.show(WebViewsActivity.this, fujian, nameList, new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                        select=position;
                        FuJianPop.hide();
                        Permission.isHaveRootActivity(WebViewsActivity.this,Permission.SD_ARR,Permission.SD_CODE,WebViewsActivity.this);

                        /*Intent intent = new Intent(context,WebViews2Activity.class);
                        intent.putExtra("bar_title", nameList.get(position));
                        intent.putExtra("url", u);
                        startActivity(intent);*/
                    }
                });
            }
        });
    }

    @Override
    protected void onRequestPermissionsSuccess(int requestCode) {
        super.onRequestPermissionsSuccess(requestCode);
        if (requestCode==Permission.SD_CODE){
            if (select!=-1){
                String u= URLAddress.HOST_PORT+urlList.get(select);
                //String u = getEncodeUrl(URLAddress.HOST_PORT+urlList.get(position));
                //String u =getEncodeUrl("http://118.178.192.37/test.docx");
                if (TextUtils.isEmpty(u)){
                    return;
                }
                 callOtherOpeanFile = new CallOtherOpeanFile(context,handler);
                callOtherOpeanFile.downLoad(u);
            }
        }
    }
    CallOtherOpeanFile callOtherOpeanFile;
    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what==0){
                Toasts.show(context,msg.obj.toString());
            }else {
                callOtherOpeanFile.openFile(new File((String)msg.obj));
            }


        }
    };

    private void initShucang() {
        right_sc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (CheckInfoUtils.isLogin(context)){
                    right_sc.setEnabled(false);
                    CommonPost.doSc(activity, type, id, new CommonPost.OnShouCangListener() {
                        @Override
                        public void onSuccess(ReslutBean bean) {
                            right_sc.setEnabled(true);
                            Toasts.show(context,bean.getStr());
                            if (bean.getCode()==0){
                                right_sc.setImageResource(R.mipmap.sc_white_no);
                            }else {
                                right_sc.setImageResource(R.mipmap.sc_white_yes);

                            }
                        }

                        @Override
                        public void onFail(String str) {
                            right_sc.setEnabled(true);
                        }
                    });
                }

            }
        });
        if (showShoucang){
            CommonPost.isCollect(activity,type, id, new OnResultListener() {
                @Override
                public void onSuccess(int requestCode, String str) {
                    right_sc.setImageResource(R.mipmap.sc_white_yes);
                }

                @Override
                public void onFailure(int requestCode, String str) {
                    right_sc.setImageResource(R.mipmap.sc_white_no);
                }
            });
        }
    }

    @Override
    protected void initData() {
        bar_title.setText(getIntent().getStringExtra("bar_title"));
    }

    private String getEncodeUrl(String urlAddress){
        String tmp="http://view.officeapps.live.com/op/view.aspx?src=";
        try {

            return tmp+URLEncoder.encode(urlAddress,"utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
        //url="http://view.officeapps.live.com/op/view.aspx?src=newteach.pbworks.com%2Ff%2Fele%2Bnewsletter.docx";
    }

}
